package com.example.minicat.server;


import ch.qos.logback.classic.spi.EventArgUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Modifier;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class Bootstrap {

    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();

    /**定义socket监听的端口号*/
    private int port = 8080;

    private String hostName = "localhost";

    private String appBase = "";

    private Mapper mapper = new Mapper();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadServer();
        setMapper();
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        /*while(true){
            Socket socket = serverSocket.accept();
            *//*System.out.println(1);

            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();*//*

            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);

            Response response = new Response(socket.getOutputStream());
//            response.outputHtml(request.getUrl());
            if(servletMap.get(request.getUrl())== null ){
                response.outputHtml(request.getUrl());
            }else{
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        }*/

        /**
         * 使用线程
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/

        /**
         * 使用线程池
         */
        while(true){
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
//            requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    //设置对应的Mapper
    private void setMapper() {
        for (Host host : mapper.getHosts()) {
            setHostContext(host);
        }
    }

    //设置对应的Mapper对应的Host
    private void setHostContext(Host host) {
        String appbase = host.getAppbase();
        File file = new File(appbase);
        File[] files = file.listFiles();
        if(files == null){
            return;
        }
        for (File file1 : files) {
            //如果是根目录下,封装Context
            //获取webapp根目录下的文件夹名
            if(file1.isDirectory()){
                String name = file1.getName();
                Context context = new Context();
                context.setName(name);
                host.getContexts().add(context);
            }
        }
        loadServlet(host);
    }

    private void loadServlet(Host host) {
        String webxmlPath = "";
        for (Context context : host.getContexts()) {
            webxmlPath = host.getAppbase()+"/"+context.getName()+ "/web.xml";
            File file = new File(webxmlPath);
            if(!file.exists() || !file.isFile()){
                throw new RuntimeException(webxmlPath + "is not found");
            }
            SAXReader saxReader = new SAXReader();
            try {
                Document document = saxReader.read(file);
                Element rootElement = document.getRootElement();
                List<Element> selectNodes = rootElement.selectNodes("//servlet");
                for (int i = 0; i < selectNodes.size(); i++) {
                    Element element =  selectNodes.get(i);
                    // <servlet-name>lagou</servlet-name>
                    Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                    String servletName = servletnameElement.getStringValue();
                    // <servlet-class>server.LagouServlet</servlet-class>
                    Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                    String servletClass = servletclassElement.getStringValue();

                    // 根据servlet-name的值找到url-pattern
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    // /lagou
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();



                    //找到LagouServlet
                    System.out.println("c.getAppbase()"+host.getAppbase());
                    System.out.println("c.getName()"+context.getName());
                    System.out.println("urlPattern"+urlPattern);
                    Class<?> c = LagouServlet.class;
                    System.out.println("c.getClass()"+c.getClass());
                    //判断是否为HttpServlet子类,且不是抽象类 Servlet.class.isAssignableFrom(c.getClass()) &&
                    if (!Modifier.isAbstract(c.getModifiers())){
                        Object o = c.newInstance();
                        String[] servletStrs = servletClass.split("\\.");
                        String servletUrl = urlPattern+"/"+(servletStrs[servletStrs.length-1].split("Servlet")[0]).toLowerCase();
                        Wrapper wrapper = new Wrapper();
                        wrapper.getServletMap().put(servletUrl,(Servlet) o);
                        System.out.println("wrapper:"+wrapper);
                        context.getWrappers().add(wrapper);
                    }
                }
                System.out.println(context.getWrappers());
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    private void loadServer() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> serverNodes = rootElement.selectNodes("//Server");
            for (int i = 0; i < serverNodes.size(); i++) {
                Element element = serverNodes.get(i);
                List<Element> serviceNodes = element.selectNodes("//Service");
                for (int j = 0; j < serviceNodes.size(); j++) {
                    Element service = serviceNodes.get(j);
                    Element connector = (Element) service.selectSingleNode("//Connector");
                    if(connector.attributeValue("port") != null){
                        port = Integer.parseInt(connector.attributeValue("port"));
                    }
                    List<Element> engineNodes = connector.selectNodes("//Engine");
                    for (Element engineNode : engineNodes) {
                        List<Element> hostNodes = engineNode.selectNodes("//Host");
                        for (Element hostNode : hostNodes) {
                            if(hostNode.attributeValue("name") != null){
                                hostName = hostNode.attributeValue("name");
                            }
                            if (hostNode.attributeValue("appBase") != null){
                                appBase = hostNode.attributeValue("appBase");
                            }
                                Host host = new Host();
                                host.setAppbase(appBase);
                                host.setName(hostName);
                                mapper.getHosts().add(host);
                        }
                    }
                }
            }
//            List<Element> selectNodes = rootElement.selectNodes("//servlet");
//            for (int i = 0; i < selectNodes.size(); i++) {
//                Element element =  selectNodes.get(i);
//                // <servlet-name>lagou</servlet-name>
//                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
//                String servletName = servletnameElement.getStringValue();
//                // <servlet-class>server.LagouServlet</servlet-class>
//                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
//                String servletClass = servletclassElement.getStringValue();
//
//
//                // 根据servlet-name的值找到url-pattern
//                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
//                // /lagou
//                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
//
//
//
//                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
//
//            }



        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
}
